class Post < ActiveRecord::Base

  self.per_page = 4

  validates :title, presence: true

  validates :content, presence: true

  validates :front_img, presence: true

  mount_uploader :front_img, ImageUploader

  has_many :photos, as: :photoable, dependent: :destroy

  scope :by_created_at_desc, -> { order('created_at desc') }

  scope :chinese, ->  { where(language: 1) }

  scope :english, -> { where(language: 2) }

  scope :traditional, ->  { where(language: 3) }

  scope :language, -> (language) { where(language: language) }

  scope :next, ->(created_at) { where("created_at < ?", created_at) }

  scope :previous, ->(created_at) { where("created_at > ?", created_at) }


  def previous(language)
    post = Post.previous(self.created_at).language(language).by_created_at_desc.last
    post.nil? ? self : post
  end

  def next(language)
    post = Post.next(self.created_at).language(language).by_created_at_desc.first
    post.nil? ? self : post
  end

end
